<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="资金审批单号" :labelCol="{span:4}" :wrapperCol="{span:20}" prop="fundApprovalNum">
              <a-input disabled v-model="model.fundApprovalNum" placeholder="请输入资金审批单号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="审批流程" :labelCol="{span:4}" :wrapperCol="{span:18}" prop="approvalProcess">
              <j-dict-select-tag
                type="list"
                :disabled="formDisabled"
                v-model="model.approvalProcess"
                dictCode="fee_application_flow"
                placeholder="请选择审批流程"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="资金类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fundingCategory">
              <j-dict-select-tag
                type="list"
                :disabled="formDisabled"
                v-model="model.fundingCategory"
                dictCode="funding_category"
                placeholder="请选择资金类别"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="财务查询人" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="financialInquirer">
              <a-input-search
                v-model="model.financeUserName"
                placeholder="请输入财务查询人"
                readonly
                enter-button
                @search="handleSelectFinanceUser1"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.financialInquirer" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <Tsl-Select-Finance-User ref="selectUserModal2"
                                   @selectFinished="selectFinanceUserOK"></Tsl-Select-Finance-User>
          <a-col :span="8">
            <a-form-model-item label="币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currency">
              <j-dict-select-tag
                type="list"
                :disabled="formDisabled"
                v-model="model.currency"
                dictCode="currency"
                placeholder="请选择币种"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="资金申请单号" :labelCol="{span:6}" :wrapperCol="{span:15}"
                               prop="fundingApplicationNum">
              <a-input disabled v-model="model.fundingRequireData?.fundingApplicationNum || model.fundingApplicationNum">
                       placeholder="请输入资金申请单号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
              <a-input-search
                v-model="model.applyUserName"
                placeholder="请输入申请人"
                readonly
                enter-button
                @search="handleSelectUser1"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.applicant" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <Tsl-Select-User-Single ref="selectUserModal1" @selectFinished="selectOK"></Tsl-Select-User-Single>
          <a-col :span="8">
            <a-form-model-item label="申请日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicantDate">
              <j-date placeholder="请选择申请日期" v-model="model.applicantDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" style="margin-top: 20px;width: 1260px;margin-left: 15px">
            <j-vxe-table
              keep-source
              :loading="table1.loading"
              :columns="updatedColumns"
              :dataSource="table1.dataSource"
              :disabled="formDisabled"
              @edit-closed="onAmountChanged"
            />
          </a-col>
          <a-col :span="24" style="margin-top: 20px;width: 1260px;margin-left: 15px">
            <j-vxe-table
              keep-source
              :loading="table2.loading"
              :columns="table2.columns"
              :dataSource="table2.dataSource"
              :disabled="formDisabled"
              @edit-closed="onAmountChanged"
            />
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="合计（大写）" :labelCol="{span:2}" :wrapperCol="{span:21}" style="margin-top: 20px"
                               prop="capitalizedAmount">
              <a-input disabled v-model="model.fundingRequireData?.bookBalancUppercase || model.bookBalancUppercase"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="开户行" :labelCol="{span:4}" :wrapperCol="{span:18}" prop="purchaseBank">
              <a-input disabled v-model="model.purchaseBank"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="账号" :labelCol="{span:4}" :wrapperCol="{span:18}" prop="purchaseAccount">
              <a-input disabled v-model="model.purchaseAccount"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="电子承兑开户行" :labelCol="{span:5}" :wrapperCol="{span:17}" prop="ebaBankName">
              <a-input disabled v-model="model.ebaBankName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="电子承兑账号" :labelCol="{span:5}" :wrapperCol="{span:17}" prop="ebaAccountNo">
              <a-input disabled v-model="model.ebaAccountNo"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, putAction } from '@/api/manage'
import TslSelectFinanceUser from '@views/business/procurement/TslSelectFinanceUser.vue'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import TslSelectUserSingle from '@comp/tsl/TslSelectUserSingle.vue'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
import JFormContainer from '@comp/jeecg/JFormContainer.vue'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'

export default {
  name: 'FundUseApprovalForm',
  mixins: [JVxeTableModelMixin],
  components: {
    TslSelectUserSingle,
    TslSelectFinanceUser,
    JFormContainer,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data() {
    return {
      model: {
        fundApprovalNum:'',
        fundingRequireData: {
          fundingApplicationNum: '',
          bookBalancUppercase: ''
        },
        purchaseBank: '',
        purchaseAccount: '',
        ebaBankName: '',
        ebaAccountNo: ''
      },
      table2: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '采购合同编号',
            key: 'code',
            type: JVXETypes.normal,
            width: '300px'
          },
          {
            title: '采购合同名称',
            key: 'name',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.normal,
            width: '200px'
          }
        ]
      },
      table1: {
        dataSource: [],
        columns: [
          {
            title: '供应商名称',
            key: 'vendorName',
            type: JVXETypes.normal,
            width: '300px'
          },
          {
            title: '所获物资',
            key: 'suppliesObtained',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '账面金额',
            key: 'bookBalance',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '到账期金额',
            key: 'receivedAmount',
            type: JVXETypes.input,
            width: '100px'
          },
          {
            title: '总申请金额',
            key: 'applicantAmount',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '已批复金额',
            key: 'approvedAmount',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '请付金额',
            key: 'pleasePayAmount',
            type: JVXETypes.inputNumber,
            width: '100px'
          },
          {
            title: '批准金额',
            key: 'endApprovalAmount',
            type: JVXETypes.input,
            width: '100px'
          },
          {
            title: '备注',
            key: 'applicantReason',
            type: JVXETypes.normal,
            width: '160px'
          }
        ]
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/procurement/fundUseApproval/add',
        edit: '/procurement/fundUseApproval/edit',
        queryById: '/procurement/fundUseApproval/queryById',
        fundings: {
          list: 'procurement/fundingApplication/list'
        }
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    updatedColumns() {
      // 如果需要动态调整列配置，可以通过 computed 返回
      return this.table1.columns
    },
  },
  created() {
    // //备份model原始值
    // this.modelDefault = JSON.parse(JSON.stringify(this.model))
    if (this.customFormData.id != null) {
      console.log("++++++++++++++++",this.customFormData)
      this.model = this.customFormData
      this.edit(this.customFormData)
    }
  },
  methods: {
    onAmountChanged({ row, column }) {
      console.log("hahaha",row)
      if (column.key === 'pleasePayAmount') {
        // 让 Vue 重新计算 computed
        row.pleasePayAmount = row.pleasePayAmount.toFixed(2)
        this.$set(this.table1.dataSource, 0, { ...row })
        // 如果你存的是 model.capitalizedAmount，也顺手写回去
        this.model.bookBalancUppercase = this.convertToChinese(row.pleasePayAmount)
      }
    },
    convertToChinese(number) {
      if (!number && number !== 0) return ''
      const fraction = ['角', '分']
      const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      const unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ]
      let num = Math.abs(number)
      let s = ''

      // 处理小数部分
      for (let i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(num * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
      }
      s = s || '整'
      num = Math.floor(num)

      // 处理整数部分
      for (let i = 0; i < unit[0].length && num > 0; i++) {
        let p = ''
        for (let j = 0; j < unit[1].length && num > 0; j++) {
          p = digit[num % 10] + unit[1][j] + p
          num = Math.floor(num / 10)
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
      }

      return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/fund_use_code'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.fundApprovalNum = res.result
        }
      })
    },
    showSupplierInfo(supplierId) {
      // 加载供应商信息
      getAction('/procurement/supplierInformation/queryById', { id: supplierId }).then((res) => {
        this.supplier = res.result
        this.model.purchaseBank = this.supplier.bank
        this.model.purchaseAccount = this.supplier.bankCode
        this.model.ebaBankName = this.supplier.eleBank
        this.model.ebaAccountNo = this.supplier.eleBankCode
      })
    },
    add(rows) {
      console.log("skdkasdj",rows)
      this.table2.dataSource= rows[0].procurementContractReviewDetail
      this.model.fundingRequireData = rows[0]
      console.log(rows[0])
      this.table1.dataSource = rows.map(item => ({
        ...item,
        arrivalPeriodAmount: item.approveAmount,
        approvedAmount: item.approveAmount,
        pleasePayAmount: item.approveAmount,
        endApprovalAmount: item.approveAmount,
      }))
      //只有有供应商才加载供应商信息
      console.log("1231311222222222")
      if (rows[0].supplierId) {
        console.log("1231311")
        this.showSupplierInfo(rows[0].supplierId)
      }
      this.model.procurementContractReviewIds= rows[0].procurementContractReviewIds
      this.getSequenceNum()
      this.edit(this.model)
    },
    edit(record) {
      console.log("edite++++++++++++++")
      if (this.table1.dataSource.length === 0) {
        this.table1.dataSource = [{
          vendorName: record.vendorName,
          suppliesObtained: record.suppliesObtained,
          bookBalance: record.bookBalance,
          arrivalPeriodAmount: record.arrivalPeriodAmount,
          applicantAmount: record.applicantAmount,
          approvedAmount: record.approvedAmount,
          pleasePayAmount: record.pleasePayAmount,
          endApprovalAmount: record.endApprovalAmount,
          applicantReason: record.applicantReason,
        }]
        this.table2.dataSource = record.procurementContractReviewDetail
      }
      this.model = Object.assign({}, record)
      this.visible = true

    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          this.model.fundingApplicationNum = this.model.fundingRequireData?.fundingApplicationNum || this.model.fundingApplicationNum
          this.model.bookBalancUppercase = this.model.fundingRequireData?.bookBalancUppercase || this.model.bookBalancUppercase
          if (
            this.table1.dataSource &&
            this.table1.dataSource.length > 0
          ) {
            let arr = this.table1.dataSource
            console.log( arr[0].pleasePayAmount)
            this.model.pleasePayAmount = arr[0].pleasePayAmount
            this.model.endApprovalAmount = arr[0].endApprovalAmount
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              if (!this.model.id) {
                this.model.dataId = res.message
                if (this.model.dataId !== '添加成功-资金'){
                  that.applySubmit(this.model)
                }
              }
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          var params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'fundUseApprovalService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
    //防止提交多次
    handleOk() {
    },
    handleSelectUser1() {
      this.$refs.selectUserModal1.visible = true
    },
    selectOK(data) {
      this.$set(this.model, 'applyUserName', data.employeeName)  // 使用Vue的响应式更新
      this.$set(this.model, 'applicant', data.employeeCode)
    },
    handleSelectFinanceUser1() {
      this.$refs.selectUserModal2.visible = true
    },
    selectFinanceUserOK(data) {
      this.$set(this.model, 'financeUserName', data.employeeName)  // 使用Vue的响应式更新
      this.$set(this.model, 'financialInquirer', data.employeeCode)
    }
  }
}
</script>